package cn.edu.ahu.aircondition.modbus.service.dao;

import cn.edu.ahu.aircondition.modbus.service.entity.AirConCtrlEntity;
import cn.edu.ahu.aircondition.modbus.service.entity.AirConStatusEntity;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import java.util.List;

/**
 *
 * Created by ahu on 2017/6/11.
 */
public class AirConCtrlDao {
    private SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();

    /**
     * 根据deviceId获取状态信息
     * @param deviceIdList 设备地址队列
     * @return 设备状态信息
     */
    public List<AirConCtrlEntity> listAirConStatusCurByDeviceId(List<Integer> deviceIdList){
        Transaction transaction = sessionFactory.getCurrentSession().getTransaction();
        transaction.begin();
        Session session = sessionFactory.getCurrentSession();
        //开始事务
        String queryString = "FROM AirConCtrlEntity AS airConCtrlEntity " +
                "WHERE airConCtrlEntity.deviceId IN :deviceIdList";
        List<AirConCtrlEntity> list =session.createQuery(queryString,AirConCtrlEntity.class).
                setParameter("deviceIdList",deviceIdList).getResultList();
        transaction.commit();
        session.close();
        return list;
    }

    /**
     * 更新数据库中空调状态信息
     * @param airConCtrlCurEntityList    空调状态信息List
     */
    public void updateAirConStatusCur(List<AirConCtrlEntity> airConCtrlCurEntityList){
        Transaction transaction = sessionFactory.getCurrentSession().getTransaction();
        transaction.begin();
        Session session = sessionFactory.getCurrentSession();
        for (AirConCtrlEntity airConCtrlEntity : airConCtrlCurEntityList){
            session.update(airConCtrlEntity);
        }
        transaction.commit();
        session.close();
    }

}
